package com.aaa.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpFilter;
import java.io.IOException;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/8/6 9:52
 * @description：我的字符编码过滤器
 * @modified By：
 * @version: 1.0
 */
@WebFilter(urlPatterns = "/*",initParams = {@WebInitParam(name = "encode",value = "UTF-8")})
public class MyEncodingFilter extends HttpFilter {
    /**
     * 默认的编码格式
     */
    String myEncode="UTF-8";
    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 执行过滤
     * @create time: 2022/8/6 9:55
     * @param request
     * @param response
     * @param chain
     * @return void
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("我的字符编码过滤器执行啦");

        request.setCharacterEncoding(myEncode);
        response.setCharacterEncoding(myEncode);
        response.setContentType("text/html;charset="+myEncode);
        //处理完业务之后，要放行,进入下一个过滤器
        chain.doFilter(request,response);
    }
   /* *//**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 过滤器的初始化
     * @create time: 2022/8/6 9:55
     * @param filterConfig
     * @return void
     *//*
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String encode = filterConfig.getInitParameter("encode");
        //在字符编码过滤器初始化的时候，优先从web.xml文件中获取字符编码的格式，如果不能获取使用默认的
        if(encode!=null){
            myEncode=encode;
        }
        System.out.println("我的字符编码过滤器初始化啦");

    }
    *//**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 过滤器的销毁
     * @create time: 2022/8/6 9:55
     * @param
     * @return void
     *//*
    @Override
    public void destroy() {
        System.out.println("我的字符编码过滤器销毁啦");
    }*/
}
